<script setup lang="ts">
import {
  Cartesian3,
  Terrain,
  Viewer,
  Color,
  HeightReference,
  PolylineGlowMaterialProperty,
  HeadingPitchRoll,
  Transforms,
} from "cesium";
import { onMounted } from "vue";
import { getModelMatrix } from "./help";

onMounted(() => {
  init();
  // test();
});

// const test = () => {
//   const positions = Cartesian3.fromDegreesArrayHeights([
//     110.78665361952665, 31.27581158988805, 100, 110.798125433302,
//     31.269269878853237, 100, 110.81348177956698, 31.269818247284093, 100,
//     110.81882620702419, 31.280669843857126, 100, 110.81017703220027,
//     31.28346776689456, 100,
//   ]);

//   const or = getModelMatrix(positions[0], positions[1]);
//   console.log(or);
// };

const init = async () => {
  // Initialize the Cesium Viewer in the HTML element with the `cesiumContainer` ID.
  const viewer = new Viewer("cesiumContainer", {
    requestRenderMode: true,
    shouldAnimate: true,
    terrain: Terrain.fromWorldTerrain(),
    infoBox: false, // If set to false, the InfoBox widget will not be created
    animation: false, // If set to false, the animation widget will not be created
    timeline: false, // If set to false, the Timeline widget will not be created
    navigationHelpButton: false, // If set to false, the navigation help button will not be created
    sceneModePicker: false, // If set to false, the scene mode picker will not be created
    baseLayerPicker: true, // If set to false, the base layer picker will not be created
    fullscreenButton: false, // If set to false, the fullscreen button will not be created
  });

  (viewer.cesiumWidget.creditContainer as HTMLElement).style.display = "none";

  const positions = Cartesian3.fromDegreesArrayHeights([
    110.78665361952665, 31.27581158988805, 100, 110.798125433302,
    31.269269878853237, 100, 110.81348177956698, 31.269818247284093, 100,
    110.81882620702419, 31.280669843857126, 100, 110.81017703220027,
    31.28346776689456, 100,
  ]);
  // console.log(positions);

  //Set the random number seed for consistent results.
  // CesiumMath.setRandomNumberSeed(3);

  viewer.entities.add({
    name: "Orange line with black outline at height and following the surface",
    polyline: {
      positions,
      width: 2,
      material: Color.ORANGE,
      clampToGround: true,
    },
  });

  // viewer.camera.flyTo({
  //   destination: Cartesian3.fromDegrees(
  //     110.78665361952665,
  //     31.27581158988805,
  //     1300
  //   ),
  //   orientation: {
  //     heading: CesiumMath.toRadians(90.0), // east, default value is 0.0 (north)
  //     pitch: CesiumMath.toRadians(0.0), // default value is 0.0 (horizontal)
  //     roll: 0,
  //   },
  //   duration: 1,
  // });

  function getOrientation(index = 0) {
    // const dict: { [key: number]: number } = {
    //   0: 40,
    //   1: -15,
    //   2: -50,
    //   3: 200,
    //   4: 225,
    // };
    const or = getModelMatrix(positions[index], positions[index + 1]);
    // var heading = CesiumMath.toRadians(dict[index]);
    // var pitch = 0;
    // var roll = 0;
    const heading = or.heading;
    const pitch = or.pitch;
    const roll = or.roll;
    var hpr = new HeadingPitchRoll(heading, pitch, roll);
    var orientation = Transforms.headingPitchRollQuaternion(
      positions[index],
      hpr
    );

    return orientation;
  }

  // const orientation = getModelMatrix(positions[0], positions[1]);

  // const pts = computeCirclularFlight();
  // const url = "/static/models/CesiumAir.glb";
  const url = "/static/models/GroundVehicle.glb";
  const modelEntity = viewer.entities.add({
    name: url,
    // position: new CallbackProperty(modelCallback, false),
    position: positions[0],
    // orientation: new VelocityOrientationProperty(pts),
    orientation: getOrientation(),
    model: {
      uri: url,
      scale: 10,
      minimumPixelSize: 16,
      heightReference: HeightReference.CLAMP_TO_GROUND,
    },
    //Show the path as a pink line sampled in 1 second increments.
    path: {
      resolution: 1,
      material: new PolylineGlowMaterialProperty({
        glowPower: 0.1,
        color: Color.YELLOW,
      }),
      width: 10,
    },
  });

  // entity.orientation = new VelocityOrientationProperty(entity.position);

  document.addEventListener("keydown", function (e) {
    // console.log("keydown", e.code);

    switch (e.code) {
      case "ArrowDown":
        break;
      case "ArrowUp":
        break;
      case "ArrowRight":
        break;
      case "ArrowLeft":
        break;
      case "KeyW":
        forward();
        break;
      case "Space":
        autoAun();
        break;
      default:
    }

    // scene.requestRender();
  });

  let flag: number | null = null;
  const autoAun = () => {
    if (flag) {
      cancelAnimationFrame(flag);
      flag = null;
    } else {
      flag = requestAnimationFrame(forward);
    }
  };

  // viewer.entities.add({
  //   name: "Line1",
  //   polyline: {
  //     positions: lines1,
  //     width: 2,
  //     material: Color.BLUE,
  //     clampToGround: true,
  //   },
  // });

  viewer.trackedEntity = modelEntity;

  let conut = 1;
  let index = 0;

  function forward() {
    // const camera = viewer.camera;
    // const direction = camera.direction;

    if (conut === 100) {
      index += 1;
      conut = 0;
    }

    if (index === positions.length - 1) {
      index = 0;
    }

    // console.log("forward--index:", index);

    // console.log("forward--modelEntity:", modelEntity);
    const pt = Cartesian3.lerp(
      positions[index],
      positions[index + 1],
      conut / 100,
      new Cartesian3()
    );

    conut++;

    const orientation = getOrientation(index);

    // viewer.camera.setView({
    //   orientation: orientation,
    // });

    // console.log(orientation);

    modelEntity.orientation = orientation as any;
    modelEntity.position = pt as any;

    viewer.scene.requestRender();

    if (flag) {
      flag = requestAnimationFrame(forward);
    }
  }
};
</script>

<template>
  <div id="cesiumContainer" class="czm-ctnr"></div>
</template>

<style lang="scss" scoped>
.czm-ctnr {
  width: 100%;
  height: 100%;
}
</style>
